package com.yuanqi.dz.dc.service.impl;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import pnbclient.helper.StringHelper;
import pnbclient.util.PnbLogFactory;
import pnblog.PnbLogging;

import com.yuanqitech.advancedpower.powerdate.DateUtil;
import com.yuanqitech.advancedpower.powerdate.PowerDateFormat;
import com.yuanqitech.powermop.dz.DZDataInterface;
import com.yuanqitech.powermop.dz.DZInfo;
import com.yuanqitech.powermop.dz.DZInfoArray;
/**
 * 河南 三门峡人民医院
 * 银联商户 对账文件解析
 * @author zjt 20171214
 *
 */
public  class SMXDZServiceImpl implements DZDataInterface{
	//940411280621804商户清算交易明细表（日终下载）20171115

	public static final PnbLogging LOG = PnbLogFactory.getLogger("DZ_EXT_LOG");
    /** 文件动态名字 */
	private static String fileName = "{merchant}商户清算交易明细表（日终下载）{date}";
	
	/** 文件名中时间的格式*/
	private static String dz_date_format = "yyyyMMdd";
	
	/** 本地路径*/
	private static String local_path = "d:\\dz\\";
	
	/** 读取明细数据开始行*/
	private static int start_row=12;  
	
	/** 文件的编码方式*/
	private static String charset = "gbk";

	public static void main(String[] args) {
		DZInfoArray  dzInfoArray=new DZInfoArray();
		String mercharnum = "940411280621804";
		String dzDate = "20171115";
		dzInfoArray = new SMXDZServiceImpl().getDZData(mercharnum, dzDate);

		DZInfo[] s= dzInfoArray.getDzInfo();
		if(null!=s && s.length > 0){
			for (int i = 0; i < s.length; i++) {
				System.out.println(s[i]);
			}
		}
	}
    
	/** 入口函数 */
	public DZInfoArray getDZData(String mercharnum, String dzDate) {
		DZInfoArray  dzInfoArray=new DZInfoArray();

		SimpleDateFormat sdf = new SimpleDateFormat(dz_date_format);
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(PowerDateFormat.getInstance(DateUtil.YYYYMMDD).parse(dzDate));
		
		String filename = fileName.replace("{merchant}", mercharnum).replace("{date}", sdf.format(calendar.getTime()));
		File file=new File(local_path, filename);

		dzInfoArray = ReadFile(file, mercharnum,dzDate);
		
		return dzInfoArray;
	}
    
	/**
	 * 解析对账文件
	 * @param file
	 * @param mercharnum
	 * @param dzDate
	 * @return
	 */
	private DZInfoArray ReadFile(File file, String mercharnum, String dzDate) {
		DZInfoArray  dzInfoArray=new DZInfoArray();

		if(!file.exists()){
			dzInfoArray.setRc("-1");
			dzInfoArray.setErrormsg(file.getName() + "文件不存在");
			dzInfoArray.setDzInfo(new DZInfo[0]);
			return dzInfoArray;
		}

		BufferedReader reader=null;

		List<DZInfo> list=new ArrayList<DZInfo>();
		try {
			reader =StringHelper.isEmpty(charset) ? new BufferedReader(new FileReader(file)): 
				new BufferedReader(new InputStreamReader(new FileInputStream(file), Charset.forName(charset)));
			String lineText = null;

			int n = 1 ;
			DZInfo  dzinfo=new DZInfo();
			while ((lineText = reader.readLine()) != null) {
				if( n>=start_row ){
					if(lineText.isEmpty()){  //明细数据解析完 break 出来 后面汇总信息不需要
						break;
					}
					
					if(lineText.indexOf("余额查询") <= 0){
						dzinfo = getDzinfo(lineText,dzDate);
						list.add(dzinfo);
					}
				}
				++n;
			}
			dzInfoArray.setRc("1");
			dzInfoArray.setDzInfo( list.toArray(new DZInfo[list.size()]));
		}catch (Exception e) {
			LOG.addError("解析对账文件"+file.getName()+"异常:"+e);
		}

		return dzInfoArray;
	} 
    
	/**
	 * 解析字符串  DZInfo对象赋值
	 * @param lineText
	 * @param dzDate
	 * @return DZInfo
	 */
	public DZInfo getDzinfo(String lineText,String dzDate){
		
		DZInfo dzinfo = new DZInfo();

		String [] arr = lineText.split("\\s+");  // 空格分割

		String amount = arr[5].replace("-", "");

		String tran_type = arr[11];
		if("消费".equals(tran_type)) tran_type = "S1";
		else if("消费撤消".equals(tran_type)) tran_type = "S2";
		else if("退货".equals(tran_type)) tran_type = "S3";

		String refernum = arr[1].substring(4,10)+arr[9];
		String bankname = arr[4];

		String trantime = dzDate + arr[1].substring(4,10);
		try {
			trantime = com.yuanqi.dz.dc.util.DateUtil.getDateTimeInterval(trantime, "yyyyMMddHHmmss", "yyyy-MM-dd HH:mm:ss");
		} catch (Exception e) {
			trantime = dzDate;
			LOG.addError("时间处理失败:" + e);
		}

		String tranCardNum = arr[2];

		dzinfo.setAmount( Float.valueOf(amount) );    //金额
		dzinfo.setTermId(arr[0]);                     //终端号
		dzinfo.setTranCode(tran_type);                //交易类型
		dzinfo.setReferNum(refernum);                 //检索参考号
		dzinfo.setBankName(bankname);                 //开户行
		dzinfo.setTrDateTime(trantime);               //交易时间
		dzinfo.setTranCardNum(tranCardNum);           //卡号

		return dzinfo;
	}
}
